const koa2Req = require('koa2-request');
const publicIp = require('public-ip') // 获取外网ip
let co = require('co');//异步控制器
// const ip = publicIp.v4().then((res) => res) // 调用模块提供的api即可获取
const gaode_key = '8a674879652195a8bc6ff51357199517'
const path = require('path')
var fs = require("fs");
const random = require('string-random');
const { saveArticle,ArticleTypeService,ArticleColumnService,getArticleService,createArticleColumnService 
    ,givePraiseArticleService,getPraiseArticleService,saveBookService,getBookListService,updateArticleService,
    saveBookVisitNumService,getBookTopService
} = require('../service/client.service')
class clientController {
    
    /**
     * 
     * @param {*} ctx 
     * @param {*} next 
     * 获取天气信息
     */
    async getWeather(ctx, next) {
        const ip_param = await publicIp.v4()
        var res = await koa2Req(`https://restapi.amap.com/v3/ip?ip=${ip_param}&output=json&key=${gaode_key}`);
        const city = JSON.parse(res.body).adcode
        console.log(city,'city')
        var res_weather = await koa2Req(`https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=${gaode_key}`)
        let weather = {data: JSON.parse(res_weather.body)}
        ctx.body = weather;
    }

    /**
     * 
     * @param {html,title,user,date,type,column,cover} ctx 
     * @param {*} next 
     * 保存文章
     */
    async saveArticle(ctx,next){
        console.log(ctx.request.body)
        const {html,user_id,title,username,date,type,column,cover,publish,desc} = ctx.request.body
        console.log(html)
        try{
            // 调用service层最好加try catch
            const res = await saveArticle(html,user_id,title,username,date,type,column,cover,publish,desc)
            console.log(res)
            // 3.返回给客户端
            ctx.body = {
                code: 1000,
                messgae: '保存成功',
                data : 'success'
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
      
    }
    /**
     * 
     * @param {*} ctx 
     * @param {*} next 
     * 文章类型
     */
    async ArticleType(ctx,next){
        try{
            const res = await ArticleTypeService()
            console.log(res,'res')
            ctx.body = {
                code: 1000,
                messgae: 'success',
                data : res
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    // 图片上传
    async Upload(ctx,next){
        // 前端的name要于此出 file相同 。 如果叫 img 前端组件也需要name='img'
        const file = ctx.request.files.file; // 获取上传文件

        console.log(ctx.request,'file')
        // 创建可读流
        const reader = fs.createReadStream(file.path);
        const random_num = random(16)
        const fileName = random_num+'.'+file.name.split('.')[1]
        let filePath = path.join(__dirname, '../app/public/uploads/') + `/${fileName}`;
        
        // 创建可写流
        const upStream = fs.createWriteStream(filePath);
        // 可读流通过管道写入可写流
        reader.pipe(upStream);
        ctx.body = {'url':`${ctx.origin}/uploads/${fileName}`}     
    }
    // 查询专栏
    async ArticleColumn(ctx,next){
        // get 获得参数 request.query
        const {user_id} = ctx.request.query
        console.log(ctx.request,ctx.request.query)
        try{
            const res = await ArticleColumnService(user_id)
            ctx.body = {
                code: 1000,
                messgae: 'success',
                data : res
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    // 创建专栏
    async createArticleColumn(ctx,next){
        const {username,user_id,column,column_detail,examine=0,examine_user='',examine_date='',result=''} = ctx.request.body
        try{
            const res = await createArticleColumnService({username,user_id,column,column_detail,examine,examine_date,result})
            ctx.body = {
                code: 1000,
                messgae: 'success',
                data : res
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    // 获得文章
    async getArticle(ctx,next){
        const {id='',username='',user_id='',type='',title='',column='',createdAtFrom='', createdAtTo='', updatedAtFrom='', updatedAtTo='',publish='',
            check='',checkdateFrom='', checkdateTo='',verifier='',currentPage=1,pageSize=10} = ctx.request.query
        try{
            const {data,total} = await getArticleService({ id,username, user_id, type, title, column, createdAtFrom, createdAtTo, updatedAtFrom, updatedAtTo, publish, check, checkdateFrom, checkdateTo, verifier,currentPage,pageSize })
            ctx.body = {
                code: 1000,
                data,
                total,
                current: currentPage,
                pageSize: pageSize
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    // 修改文章
    async updateArticle(ctx,next){
        const {id='',type='',title='',column='',publish=0,html='',reason='',cover='',
        check='',verifier=''} = ctx.request.body
        try{
            const res = await updateArticleService({ id,type,title,column,publish,html,reason,cover,
            check,verifier })
            ctx.body = {
              res
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    /**
     *     我的
     */
    // 我点赞的文章
     async givePraiseArticle(ctx,next){
        const {title='',column='',operateuser_id,currentPage=1,pageSize=10} = ctx.request.query
        try{
            const res = await givePraiseArticleService({title,column,operateuser_id,currentPage,pageSize})
            ctx.body = {
                code: 1000,
                data:res
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    // 点赞我的
    async getPraiseArticle(ctx,next){
        const {title='',column='',authoruser_id,currentPage=1,pageSize=10} = ctx.request.query
        try{
            const res = await getPraiseArticleService({title,column,authoruser_id,currentPage,pageSize})
            ctx.body = {
                code: 1000,
                data:res
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    // 我点赞的count


    // 点赞我的count

   

     /**
      *   图书分享
      */
    async saveBook(ctx,next){
        const {title,author,img_url,file_url,type=''} = ctx.request.body
        try{
            // 调用service层最好加try catch
            const res = await saveBookService({title,author,img_url,file_url,type})
            console.log(res)
            // 3.返回给客户端
            ctx.body = {
                code: 1000,
                messgae: '保存成功',
                data : 'success'
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    async getBookList(ctx,next){
        const {title='',author='',type='',pageSize=8, currentPage=1} = ctx.request.query
        try{
            // 调用service层最好加try catch
            const {data,total} = await getBookListService({title,author,type,pageSize,currentPage})
            // 3.返回给客户端
            ctx.body = {
                code: 1000,
                data,
                total,
                current: currentPage,
                pageSize: pageSize
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    async saveBookVisitNum(ctx,next){
        const {title='',author='',file_url='',id} = ctx.request.body
        try{
            // 调用service层最好加try catch
            const res = await saveBookVisitNumService({title,author,file_url,id})
            console.log(res)
            // 3.返回给客户端
            ctx.body = {
                code: 1000,
                messgae: '保存成功',
                data : 'success'
            }
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    async getBookTop(ctx,next){
        try{
            // 调用service层最好加try catch
            const res= await getBookTopService()
            // 3.返回给客户端
            ctx.body ={
                code:1000,
                data:res
            }
            
        }catch(err){
            console.log(err)
            ctx.app.emit('error',err)
        }
    }
    /**
     * 
     *    PV 用户访问量
     */
    // async pageView(ctx,next){
    //     const {id} =  ctx.request.query
    //     try{
    //         const res = await pageViewService({id})
    //         ctx.body ={
    //             code:1000,
    //             res
    //         }
    //     }catch(err){

    //     }  
    // }
    /**
     * 
     *  ArticleLiked
     */
    //  async givePraise(ctx,next){
    //     const { id,author,authoruser_id,operateuser,title,operateuser_id} =  ctx.request.body
    //     console.log(id,author,authoruser_id,operateuser,title,operateuser_id)
    //     try{
    //         const res = await givePraiseService({id,author,authoruser_id,operateuser,title,operateuser_id})
    //         console.log(res,'🐯')
    //         ctx.body ={
    //             code:1000,
    //             data:res
    //         }
    //     }catch(err){
    //         console.log(err,'err')
    //     }  
    // }
}
// 导出实例化的对象
module.exports = new clientController()

















// function send(params) {
//     return new Promise((resolve, reject)=>{
//       request(`https://restapi.amap.com/v3/ip?ip=${ip_param}&output=json&key=${gaode_key}`, function (error, response, body) {
//        })
//   })
// }
//   let res = await co(function name() {
//       let req_res = send()
//       return req_res
//   })
//   console.log(res)
//   ctx.body = res
// }


// request(`https://restapi.amap.com/v3/ip?ip=${ip_param}&output=json&key=${gaode_key}`, function (error, response, body) {
          

//     let city = JSON.parse(body).adcode
//     data = JSON.parse(body).adcode
//     console.log(data)
//     ctx.body = await data
//     console.log(data.adcode) // }
//    request(`https://restapi.amap.com/v3/weather/weatherInfo?city=${city}&key=${gaode_key}`, function (err, response, body){
//         data = body
//         console.log(data)
//         ctx.body = 'aaa'
//       })

// })